<template>
  <el-upload
    class="avatar-uploader"
    action="https://jsonplaceholder.typicode.com/posts/"
    :show-file-list="false"
    :before-upload="beforeAvatarUpload"
    :http-request="uploadImg"
  >
    <!-- (自动上传)action是上传地址 人资项目不需要 人资项目(手动上传)  -->
    <!-- show-file-list不展示列表 -->
    <img v-if="value" :src="value" class="avatar">
    <i v-else class="el-icon-plus avatar-uploader-icon" />
  </el-upload>

</template>

<script>
import COS from 'cos-js-sdk-v5'
export default {
  props: {
    value: {
      type: String,
      default: ''
    }
  },
  methods: {
    uploadImg({ file }) {
      const cos = new COS({
        SecretId: 'AKIDlPs9FCwVv9A0gFpMuNpHajhS0KSM3Yqv',
        SecretKey: 'whFbjgRyJUUHtKbjeN4pVBYq12vfHlBU'
      })
      cos.putObject({
        Bucket: 'avator-rlzy-1317949367', // 存储桶名称
        Region: 'ap-shanghai', // 地域名称
        Key: file.name, // 文件名称
        // StorageClass: 'STANDARD', // 固定值
        Body: file // 文件对象
      }, (err, data) => {
        if (err) {
          this.$message.error('上传失败')
        } else {
          this.$emit('input', 'http://' + data.Location)
          this.$message.success('上传成功')
        }
      })
    },
    // 检查函数 判断文件的类型还有大小 return  true(继续上传)/false(停止上传)
    beforeAvatarUpload(file) {
      // jpeg png gif bmp
      const res = ['image/jpeg', 'image/png', 'image/gif', 'image/bmp'].includes(file.type)
      //  参数为上传文件 自己决定要不要继续上传 不想继续上传 return false / 失败 promise reject()
      if (file.size / 1024 / 1024 < 2 && res) { return true }
      return false
    }
  }
}
</script>

<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
